/**
 * Created by pkd on 14-3-18.
 */
require("../util/bootloader.js");
var CONFIG = require("../config.js");
var mysql = require('mysql');

var mysqlDb = function () {
    this.pool = null;
    this._init();
};

mysqlDb.prototype._init = function () {
    this.pool = mysql.createPool(CONFIG.GM_DB);
    console.log("mysqlDb is initialized.\n");
};

//需要在调用方法中手动释放连接
mysqlDb.prototype.getConnection = function (cb) {
    var pool = this.getPool();
    if (pool) {
        pool.getConnection(function (err, connection) {
            cb(err, connection);
        })
    } else {
        cb("db factory is not init.");
    }
};

// cbQuery 返回true的情况下需要手动释放，其他情况会自动释放。
mysqlDb.prototype.poolQuery = function (sql, data, cbIfNoConnection, cbQuery) {
    var pool = this.getPool();
    if (pool) {
        pool.getConnection(function (err, connection) {
            if(err){
                if(cbIfNoConnection) cbIfNoConnection(err, connection);
                if(connection) connection.release();
                return;
            }
            connection.query(sql, data, function (error, result) {
                if(!cbQuery){
                    connection.release();
                    return;
                }
                if(!cbQuery(error, result, connection)){
                    connection.release();
                }
            });
        })
    } else {
        if(cbIfNoConnection) cbIfNoConnection("db factory is not init.");
    }
};
//获取连接池对象
mysqlDb.prototype.getPool = function () {
    if (!this.pool) {
        this._init();
    }
    return this.pool;
};

//通用sql执行方法，回调函数参数和原始api类似
mysqlDb.prototype.query = function (sql, values, cb) {
    var self = this;
    var pool = self.getPool();
    pool.query(sql, values, cb);
};
module.exports = new mysqlDb();


